/*
 * @Author: yangzonglong
 * @Date: 2021-06-30 14:57:27
 * @version: v1.0.0
 * @Descripttion: 上传控件
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-05 12:14:43
 * @Auditor:
 */
import React, { useState, useCallback, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Upload, Form, message } from 'antd';
import { Icon } from '@library';
import { UploadProps as AntdUploadProps } from 'antd/lib/upload/interface';
import { PlusOutlined } from '@ant-design/icons';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from './../../interface';
import { FormItemProps } from '../components/InputFormItemController';
import { fileDataSource } from './MediaController';

import styles from './style.module.scss';

const UPLOAD_URL = '/bk/uploadIpfs/workflow';
const deleteIconStyle: React.CSSProperties = { fontSize: '16px', color: '#fff' };
const divStyle: React.CSSProperties = { marginBottom: '20px', position: 'relative' };

interface RefProps {
  getData(): any;
}

export interface MediaProps extends CanvasItemProps {
  mediaProps?: AntdUploadProps & {
    maxCount?: number;
    maxSize?: string; // 最大上传体积 MB
  };
  initialValue?: any[];
  formItemProps?: FormItemProps;
  disabled?: boolean;
  style?: React.CSSProperties;
}
// 音频图片5M以内  视频100M以内
const mapType = [
  {
    type: ['image/jpeg', 'image/png', 'image/gif'],
    render: (filename: string) => <img style={{ maxWidth: '100%', height: 'auto' }} src={'/bk/getFile/' + filename} alt="" />,
    maxSize: 5,
    tips: '图片',
  },
  {
    type: ['audio/mpeg', 'audio/x-m4a', 'audio/mp4'],
    render: (filename: string) => <audio src={'/bk/getFile/' + filename} controls />,
    maxSize: 5,
    tips: '音频',
  },
  {
    type: ['video/mp4'],
    render: (filename: string) => <video style={{ maxWidth: '100%', height: 'auto' }} src={'/bk/getFile/' + filename} controls />,
    maxSize: 100,
    tips: '视频',
  },
];

const ComponentUpload = (props: MediaProps, ref: React.Ref<RefProps>) => {
  const { disabled, mediaProps, formItemProps, domComplete, initialValue, ...canvasProps } = props;

  const [fileList, setFileList] = useState<any[]>([]);

  useEffect(() => {
    if (initialValue) setFileList(initialValue);
  }, [initialValue]);

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  const beforeUpload = useCallback(
    (file, fileList) => {
      window.$app.showLoading();

      let _mapItem = mapType.filter((ele) => ele.type.includes(file.type))?.[0];

      if (_mapItem?.maxSize * 1024 * 1000 < file.size) {
        // 转成k 对比
        message.warning(`${_mapItem.tips}不能超过${_mapItem.maxSize} MB`);
        window.$app.hideLoading();
        return Upload.LIST_IGNORE;
      }

      if (!mediaProps?.maxCount) return true; // 未限制体积未限制数量 允许上传

      if (mediaProps?.maxCount && mediaProps.maxCount === fileList.length - 1) {
        message.warning(`总数量不能超过${mediaProps.maxCount}`);
        window.$app.hideLoading();
        return Upload.LIST_IGNORE;
      }

      return true;
    },
    [mediaProps]
  );

  const normFile = useCallback((e: any) => {
    if (Array.isArray(e)) return e;
    return e && e.fileList;
  }, []);

  const onChange = useCallback((e: any) => {
    if (e.file?.response) {
      window.$app.hideLoading();
      setFileList((prev) => prev.concat([e.file?.response]));
    }
  }, []);

  useImperativeHandle(ref, () => ({
    getData() {
      return fileList;
    },
  }));

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;

  return (
    <Form.Item {...canvasProps} {...props.formItemProps} style={{ width: '100%' }} label={label} valuePropName="fileList" getValueFromEvent={normFile}>
      <div style={{ overflow: 'hidden', display: 'flex', flexWrap: 'wrap' }}>
        {fileList.map((item, index) => {
          let _mapItem = mapType.filter((ele) => ele.type.includes(item.mimetype))?.[0];
          return (
            <div style={{ ...props.formItemProps?.style, ...divStyle }}>
              <div className={styles.item}>
                {_mapItem?.render(item.filename)}
                {!disabled && <div className={styles.delicon}>
                  <Icon style={deleteIconStyle} icon="&#xe66d;" onClick={() => setFileList((prev) => prev.filter((item, i) => index !== i))} />
                </div>}
              </div>
            </div>
          );
        })}
      </div>

      {!disabled && (
        <Upload
          {...mediaProps}
          accept={mediaProps?.accept || fileDataSource.join(',')}
          action={UPLOAD_URL}
          beforeUpload={beforeUpload}
          onChange={onChange}
          showUploadList={false}
        >
          <div className={styles.uploadbtn}>
            <PlusOutlined style={{ fontSize: '28px' }} />
            <div>{localStorage.i18nextLng === 'en' ? 'Insert Media' : '插入多媒体'}</div>
          </div>
        </Upload>
      )}
    </Form.Item>
  );
};

export default forwardRef(ComponentUpload);
